import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header

from common.log.log import log
from config import conf


class Email:
    """
    邮件初始化发件人，密码，收件人列表
    """

    def __init__(self, server_host=None, user=None, fromaddr=None, password=None, toaddrs=None):
        if fromaddr == None:
            self.fromaddr = conf.EMAIL_FROMADDR
            self.password = conf.EMAIL_PASSWORD
            self.user = conf.EMAIL_USER
        else:
            self.fromaddr = fromaddr
            self.password = password
            self.user = user

        if toaddrs == None:
            self.toaddrs = conf.EMAIL_TOADDR
        else:
            self.toaddrs = toaddrs

        if server_host == None:  # 设置邮件服务器默认值
            self.server = smtplib.SMTP()
            self.server.connect('mail.inovance.com', 25)
        else:
            self.server = smtplib.SMTP(server_host)
        self.message = MIMEMultipart('related')  # 邮件体内容

    def set_message(self, name, title, content, filelist):
        self.message = MIMEMultipart('related')  # 邮件体
        self.message['From'] = Header(f"{name}<{self.fromaddr}>", 'utf-8')  # 发件人名称和地址
        self.message['Subject'] = Header(title, 'utf-8')  # 邮件主
        self.message['To'] = ','.join(self.toaddrs)  # 题
        self.message.attach(MIMEText(content, 'html', 'utf-8'))  # 邮件内容
        if filelist != None:  # 邮件附件
            for file in filelist:
                fileApart = MIMEApplication(open(file, 'rb').read(), file.split('.')[-1])
                fileApart.add_header('Content-Disposition', 'attachment', filename=file.split("\\")[-1])
                self.message.attach(fileApart)

    # 发送邮件
    def send_message(self):
        try:
            self.server.login(self.user, self.password)
            self.server.sendmail(self.fromaddr, self.toaddrs, self.message.as_string())
            print(f'邮件发送成功！收件人：{self.toaddrs}')
            self.server.quit()
        except smtplib.SMTPException as e:
            print('邮件发送失败！错误信息：', e)


def send_default_email():
    log.info("自动化平台正在发送邮件……")
    my_email = Email(user='Robottest', fromaddr='Robottest@qq.com',
                     toaddrs=['test3@qq.com', 'test1@qq.com', "test2@qq.com"],
                     password='xxxxxx')
    my_email.set_message(
        name="Robottest",
        title="UI自动化平台测试执行完毕提醒！",
        content='''
            您的测试报告已生成，请注意查收！报告内容以附件形式展示（Excel+网页）\n
            ''',
        filelist=conf.FILE_LIST
    )
    my_email.send_message()
    log.info("邮件发送完毕！")


if __name__ == '__main__':
    send_default_email()
